﻿using System;
using System.Web;
using System.Web.Caching;

namespace SYH.Comp
{
    /// <summary>
    /// 缓存操作类
    /// </summary>
    public class DataCache
    {
        /// <summary>
        /// 获取Cache是否为空 有cache返回true，无cache返回false:
        /// </summary>
        /// <param name="name"></param>
        /// <returns>为空返回 false 不为空返回true</returns>
        public static bool IsHasCache(string name)
        {
            return HttpContext.Current.Cache[name] != null;
        }
        /// <summary>
        /// 获取当前应用程序指定name的Cache值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static object GetCache(string name)
        {
            return HttpContext.Current.Cache[name];
        }
        /// <summary>
        /// 获取当前应用程序指定name的Cache值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static void RemoveCache(string name)
        {
            HttpContext.Current.Cache.Remove(name);
        }
        /// <summary>
        /// 设置当前应用程序指定name的Cache值
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void SetCache(string name, object value)
        {
            if (value == null) return;
            HttpContext.Current.Cache.Insert(name, value);
        }
        /// <summary>
        /// 设置缓存对象
        /// </summary>
        /// <param name="name">缓存对象名</param>
        /// <param name="value">缓存对象</param>
        /// <param name="timespan">过期时间/秒</param>
        /// <param name="absolute">绝对过期/非绝对</param>
        public static void SetCache(string name, object value, double timespan, bool absolute)
        {
            if (absolute)
            {
                HttpContext.Current.Cache.Insert(name, value, null, DateTime.Now.AddSeconds(timespan),
                                                 Cache.NoSlidingExpiration);
            }
            else
            {
                HttpContext.Current.Cache.Insert(name, value, null, Cache.NoAbsoluteExpiration,
                                                 TimeSpan.FromSeconds(timespan));
            }
        }
        /// <summary>
        /// 设置缓存对象 半小时 绝对过期
        /// </summary>
        /// <param name="name">缓存对象名</param>
        /// <param name="value">缓存对象</param>
        public static void SetCacheAtTime(string name, object value)
        {
            if (value == null) return;
            HttpContext.Current.Cache.Insert(name, value, null, DateTime.Now.AddSeconds(1800), Cache.NoSlidingExpiration);
        }

 
    }
}
